package controllers
import (
	"github.com/astaxie/beego"
	"io/ioutil"
	"github.com/astaxie/beego/logs"
	"log"
	"strings"
	"fmt"
)

type UpLoadController struct {
	beego.Controller //这里相当于继承beego.Controller
}

//重写Get方法
func (filed *UpLoadController) Get() {
	filed.Ctx.WriteString("hello go")
}


func (filed *UpLoadController) FileS()  {
	filed.TplName="upload.html"
}

func (filed *UpLoadController) FileD()  {
	// 读取文件信息
	f, h, err := filed.GetFile("filename")

	if err != nil {
		log.Fatal("读取文件错误", err)
	}

	// 延迟关闭文件
	defer f.Close()

	//查看文件可忽略 可保存文件以后在读取
	data, err := ioutil.ReadAll(f)
	if err != nil {
		logs.Debug(err)
	}
	fmt.Println(h.Filename)
	// filed.Ctx.WriteString(string(data))
	// 保存文件, 本地文件路径static/upload/上传文件名
	// 需要提前创建好static/upload目录
	if strings.HasSuffix(h.Filename, ".png") ||
		strings.HasSuffix(h.Filename, ".jpg") ||
		strings.HasSuffix(h.Filename, ".jpeg") ||
		strings.HasSuffix(h.Filename, ".webp") ||
		strings.HasSuffix(h.Filename, ".GIF") ||
		strings.HasSuffix(h.Filename, ".BMP") ||
		strings.HasSuffix(h.Filename, ".SVG"){
		filed.SaveToFile("filename", "files/upload/image/" + h.Filename)

	} else if strings.HasSuffix(h.Filename, ".mp3") ||
		strings.HasSuffix(h.Filename, ".flac") ||
		strings.HasSuffix(h.Filename, ".wav") ||
		strings.HasSuffix(h.Filename, ".ape"){
		filed.SaveToFile("filename", "files/upload/music/" + h.Filename)
	} else if strings.HasSuffix(h.Filename, ".mp4") ||
		strings.HasSuffix(h.Filename, ".AVI") ||
		strings.HasSuffix(h.Filename, ".mpg") ||
		strings.HasSuffix(h.Filename, ".mpeg") ||
		strings.HasSuffix(h.Filename, ".3gp") ||
		strings.HasSuffix(h.Filename, ".mov") ||
		strings.HasSuffix(h.Filename, ".mkv") ||
		strings.HasSuffix(h.Filename, ".flv") ||
		strings.HasSuffix(h.Filename, ".vob"){
		filed.SaveToFile("filename", "files/upload/video/" + h.Filename)
	}  else if strings.HasSuffix(h.Filename, ".txt") ||
		strings.HasSuffix(h.Filename, ".pdf") ||
		strings.HasSuffix(h.Filename, ".doc") ||
		strings.HasSuffix(h.Filename, ".docx") ||
		strings.HasSuffix(h.Filename, ".xlsx") ||
		strings.HasSuffix(h.Filename, ".xls") ||
		strings.HasSuffix(h.Filename, ".docx"){
		filed.SaveToFile("filename", "files/upload/docs/" + h.Filename)
	} else {
		filed.SaveToFile("filename", "files/upload/other/" + h.Filename)
	}

	filed.Ctx.WriteString("upload success")

}

